<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <!-- 警告条 -->
      <el-alert :closable="false"
                title="添加商品信息"
                type="info"
                center
                show-icon>
      </el-alert>
      <!-- 步骤条 -->
      <el-steps align-center
                :active="activeIndex-0"
                finish-status="success">
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <!-- tabs标签页 -->
      <el-form label-position="top"
               ref="addGoodsFormRef"
               :rules="addGoodsFormRules"
               :model="addGoodsForm">
        <el-tabs @tab-click="tabClick"
                 :before-leave="tabsBeforeLeave"
                 v-model="activeIndex"
                 tab-position="left">
          <el-tab-pane label="基本信息"
                       name="0">
            <el-form-item prop="goods_name"
                          label="商品名称">
              <el-input v-model="addGoodsForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item prop="goods_price"
                          label="商品价格">
              <el-input type="number"
                        v-model="addGoodsForm.goods_price"></el-input>
            </el-form-item>
            <el-form-item prop="goods_weight"
                          label="商品重量">
              <el-input type="number"
                        v-model="addGoodsForm.goods_weight"></el-input>
            </el-form-item>
            <el-form-item prop="goods_number"
                          label="商品数量">
              <el-input type="number"
                        v-model="addGoodsForm.goods_number"></el-input>
            </el-form-item>
            <el-form-item prop="goods_number"
                          label="商品分类">
              <el-cascader v-model="addGoodsForm.goods_cat"
                           :options="goodsCate"
                           :props="cascaderProps"
                           @change="cascaderHandleChange"></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数"
                       name="1">
            <el-form-item v-for="item in manyData"
                          :key="item.attr_id"
                          :label="item.attr_name">
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox border
                             v-for="(item,index) in item.attr_vals"
                             :key="index"
                             :label="item"></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性"
                       name="2">
            <el-form-item v-for="item in onlyData"
                          :key="item.attr_id"
                          :label="item.attr_name">
              <el-input v-model="item.attr_vals">
              </el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片"
                       name="3">
            <el-upload class="upload-demo"
                       action="http://liufusong.top:8888/api/private/v1/upload"
                       :headers="uploadHeaders"
                       :on-preview="handlePreview"
                       :on-remove="handleRemove"
                       :on-success="uploadSuccess"
                       list-type="picture">
              <el-button size="small"
                         type="primary">点击上传</el-button>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容"
                       name="4">
            <quill-editor v-model="addGoodsForm.goods_introduce">
            </quill-editor>
            <el-button @click="addGoods"
                       style="margin-top:20px"
                       type="primary">添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
    <!-- 预览图片 -->
    <el-dialog :visible.sync="previewImgDialogVisible"
               width="50%">
      <img style="width:100%;"
           :src="imgUrl" />
    </el-dialog>
  </div>
</template>

<script>
import { cloneDeep } from 'lodash'
export default {
  data () {
    return {
      activeIndex: 0,
      addGoodsForm: {
        goods_name: '',
        goods_price: 0,
        goods_weight: 0,
        goods_number: 0,
        goods_cat: [],
        pics: [],
        attrs: [],
        goods_introduce: ''
      },
      addGoodsFormRules: {
        goods_name: [
          { required: true, message: '请输入商品名称', trigger: 'blur' },
          { min: 2, max: 8, message: '长度在 2 到 8 个字符', trigger: 'blur' }
        ],
        goods_price: [
          { required: true, message: '请输入商品价格', trigger: 'blur' }
        ],
        goods_weight: [
          { required: true, message: '请输入商品重量', trigger: 'blur' }
        ],
        goods_number: [
          { required: true, message: '请输入商品数量', trigger: 'blur' }
        ]
      },
      goodsCate: [],
      cascaderProps: {
        expandTrigger: 'hover',
        label: 'cat_name',
        value: 'cat_id'
      },
      manyData: [],
      onlyData: [],
      uploadHeaders: {
        Authorization: sessionStorage.getItem('token')
      },
      previewImgDialogVisible: false,
      imgUrl: ''
    }
  },

  created () {
    this.getGoodsCate()
  },
  computed: {
    cateId () {
      if (this.addGoodsForm.goods_cat.length !== 3) {
        return null
      }
      return this.addGoodsForm.goods_cat[2]
    }
  },

  methods: {
    async getGoodsCate () {
      const { data: res } = await this.$axios.get('categories')
      if (res.meta.status !== 200) return this.$message.error('获取失败')
      this.goodsCate = res.data
    },
    cascaderHandleChange () {
      if (this.addGoodsForm.goods_cat.length !== 3) {
        this.addGoodsForm.goods_cat = []
      }
    },
    tabsBeforeLeave (activeName, oldName) {
      if (oldName === '0' && this.addGoodsForm.goods_cat.length !== 3) {
        this.$message.error('请选择三级商品分类')
        return false
      }
    },
    async getGoodsParams (sel) {
      const { data: res } = await this.$axios.get('categories/' + this.cateId + '/attributes', {
        params: {
          sel: sel
        }
      })
      if (res.meta.status !== 200) return this.$message.error('获取失败')
      if (sel === 'many') {
        res.data.forEach(item => {
          item.attr_vals = item.attr_vals === '' ? [] : item.attr_vals.split(',')
        })
        this.manyData = res.data
      } else {
        this.onlyData = res.data
      }
    },
    tabClick () {
      if (this.activeIndex === '1') {
        this.getGoodsParams('many')
      } else if (this.activeIndex === '2') {
        this.getGoodsParams('only')
      }
    },
    handlePreview (file) {
      this.previewImgDialogVisible = true
      this.imgUrl = 'http://liufusong.top:8888/' + file.response.data.tmp_path
    },
    handleRemove (file) {
      const index = this.addGoodsForm.pics.findIndex(item => {
        return item.pic === file.response.data.tmp_path
      })
      this.addGoodsForm.pics.splice(index, 1)
    },
    uploadSuccess (res) {
      console.log('图片上传成功', res)
      this.addGoodsForm.pics.push({
        pic: res.data.tmp_path
      })
    },
    addGoods () {
      this.$refs.addGoodsFormRef.validate(async flag => {
        if (!flag) return this.$message.error('请完善基本信息必填项')

        // const form = JSON.parse(JSON.stringify(this.addGoodsForm))
        const form = cloneDeep(this.addGoodsForm)
        form.goods_cat = form.goods_cat.join(',')
        this.manyData.forEach(item => {
          form.attrs.push({ attr_id: item.attr_id, attr_value: item.attr_vals.join(',') })
        })
        this.onlyData.forEach(item => {
          form.attrs.push({ attr_id: item.attr_id, attr_value: item.attr_vals })
        })
        console.log(form, this.addGoodsForm)
        const { data: res } = await this.$axios.post('goods', form)
        if (res.meta.status !== 201) return this.$message.error('获取失败')
        this.$message.success('创建成功')
        this.$router.push('/goods')
      })
    }
  }
}
</script>

<style scoped lang='less'>
.el-steps {
  margin: 20px auto;
}
/deep/.el-step__title {
  font-size: 12px;
}
.el-checkbox {
  margin-right: 0;
}
/deep/.ql-editor {
  height: 400px;
}
</style>
